package com.apes.scm.masterdata.finance.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.finance.model.AmtReceipt;
import com.apes.scm.masterdata.finance.repository.AmtReceiptRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @Auther: linwz
 * @Date: 2018/8/13 09:51
 */
@Service("amtReceiptService")
public class AmtReceiptService extends DomainService {
    @Autowired
    AmtReceiptRepository amtReceiptRepository;
    /**
     * 保存
     * @param request
     * @return
     */
    public AmtReceipt save(SimpleRequest request){
        AmtReceipt amtReceipt = request.getO(AmtReceipt.class);
        return amtReceiptRepository.saveAndFlush(amtReceipt);
    }

    public AmtReceipt update(SimpleRequest request){
        AmtReceipt amtReceipt = request.getO(AmtReceipt.class);
        return amtReceiptRepository.saveAndFlush(amtReceipt);
    }

    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Integer versions = request.get("version");
        AmtReceipt amtReceipt = request.getO(AmtReceipt.class);
        if (amtReceipt == null) throw new RuntimeException("资金收入类型【"+ id +"】在系统中不存在。");
        if (amtReceipt.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        amtReceiptRepository.delete(amtReceipt);
        return "删除成功";
    }

    /**
     * 查询
     * @param request
     * @return
     */
    public Page<AmtReceipt> findAll(SimpleRequest request){
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return amtReceiptRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }
}
